package per.destiny.seckill.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import per.destiny.seckill.pojo.Order;
import per.destiny.seckill.pojo.SeckillOrder;
import per.destiny.seckill.pojo.User;
import per.destiny.seckill.service.GoodsService;
import per.destiny.seckill.service.OrderService;
import per.destiny.seckill.service.SeckillOrderService;
import per.destiny.seckill.vo.GoodsVo;
import per.destiny.seckill.vo.RespBeanEnum;

@Controller
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SeckillOrderService seckillOrderService;

    @Autowired
    private OrderService orderService;

    @RequestMapping(value = "/doSeckill", method = RequestMethod.GET)
    public String toList(Model model, User user, Long goodsId) {
        if (user == null) {
            return "login";
        }
        model.addAttribute("user", user);
        GoodsVo goods = goodsService.findGoodsVoById(goodsId);
        // 判断库存
        if (goods.getStockCount() < 1) {
            model.addAttribute("errorMsg", RespBeanEnum.EMPTY_SOCKET.getMessage());
            return "seckillFail";
        }
        // 判断是否重复抢购
        SeckillOrder seckillOrder = seckillOrderService.getOne(user.getId(), goodsId);
        if (seckillOrder != null) {
            model.addAttribute("errMsg", RespBeanEnum.REPEATE_ERROR.getMessage());
            return "seckillFail";
        }
        Order order = orderService.seckill(user, goods);
        model.addAttribute("order", order);
        model.addAttribute("goods", goods);
        return "orderDetail";
    }

}
